package cn.hznc.controller.service.process.logic;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hznc.domain.entity.ProcessBomEntity;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author Administrator
 * @Date 2023/3/16 9:04
 */
public class ProcessBomLogic {
    private final ProcessBomDo processBomDo;

    private final List<ProcessBomEntity> originProcessBomList;

    private final List<ProcessBomEntity> updateProcessBomList;

    public ProcessBomLogic(List<ProcessBomEntity> originProcessBomList, List<ProcessBomEntity> updateProcessBomList) {
        this.originProcessBomList = originProcessBomList;
        this.updateProcessBomList = updateProcessBomList;
        this.processBomDo=new ProcessBomDo();
    }

    /**
     * 获取处理后的业务模型
     *
     * @return subProgramDo
     */
    public ProcessBomDo getProcessBomDo() {
        return processBomDo;
    }

    /**
     * 分离增删改数据
     */
    public void buildProcessBomDo(){
        if (CollectionUtil.isEmpty(originProcessBomList)){
            processBomDo.addCreateElement(updateProcessBomList);
            return;
        }
        if (CollectionUtil.isEmpty(updateProcessBomList)){
            processBomDo.addDeleteElement(originProcessBomList);
            return;
        }
        // 比对id判断，对删除，修改，新增
        List<Integer> ids = originProcessBomList.stream().map(ProcessBomEntity::getId).collect(Collectors.toList());
        List<Integer> updateIds = updateProcessBomList.stream().filter(updateProcessCraft-> ObjectUtil.isNotNull(updateProcessCraft.getId())).map(ProcessBomEntity::getId).collect(Collectors.toList());
        for (ProcessBomEntity processBomEntity : updateProcessBomList) {
            // 添加修改元素
            if (ids.contains(processBomEntity.getId())) {
                processBomDo.addUpdateElement(processBomEntity);
            }
            // 添加新增元素
            if (ObjectUtils.isEmpty(processBomEntity.getId())){
                processBomDo.addCreateElement(processBomEntity);
            }
        }
        for (ProcessBomEntity processBomEntity : originProcessBomList) {
            // 添加删除元素
            if (!updateIds.contains(processBomEntity.getId())){
                processBomDo.addDeleteElement(processBomEntity);
            }
        }
    }
}
